#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QModbusRtuSerialClient>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <QTimer>
#include <QMessageBox>
#include <QStringList>
#include "crc.h"
#include <QSettings>
#include <QFileInfo>
#include <QDir>
#include <QFont>
#include <QDate>
#include <QDesktopServices>
#include <QUrl>

QString failStyle = "color: black;background-color: red";
QString passStyle = "color: black;background-color: springgreen";
QString defaultStyle = "color: black;background-color: white";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QFont f = ui->lb_tips->font();
    f.setPointSize(36);
    ui->lb_tips->setFont(f);
    ui->lb_tips->setAlignment(Qt::AlignCenter);
    this->setWindowTitle(QString("盐氯机M款工厂测试软件 ")+SOFT_VER);

    modbusDevice = new QModbusRtuSerialClient(this);
    Fill_SerialPort();
    m_serialPortTimer = new QTimer();
    connect(m_serialPortTimer,&QTimer::timeout,this,&MainWindow::Fill_SerialPort);
    m_serialPortTimer->start(1000);

    m_testTimer = new QTimer();
    connect(m_testTimer,&QTimer::timeout,this,&MainWindow::Test_Main);

    QStringList item;
    item.append("F1");
    item.append("F2");
    item.append("F3");
    item.append("F4");
    ui->cb_deviceCfg->addItems(item);
    ui->cb_deviceCfg->setCurrentIndex(0);
    m_deviceCfg = 0;

    item.clear();
    item.append("10g");
    item.append("16g");
    item.append("22g");
    item.append("28g");
    ui->cb_electrolytic->addItems(item);
    ui->cb_electrolytic->setCurrentIndex(1);
    m_electrolytic = 20;    // 根据上面选择的索引确定

    item.clear();
    item.append("PCBA");
    item.append("整机");
    ui->cb_testType->addItems(item);
    ui->cb_testType->setCurrentIndex(0);
    memset(&m_valueRange,0,sizeof(m_valueRange));
    if(!Read_Settings(TEST_PCBA))
    {
        Read_Settings(TEST_PCBA);
    }

    QSize buttonIconSize(68,68);
    ui->pb_boost->setIcon(QIcon(":/image/boost_.png"));
    ui->pb_boost->setIconSize(buttonIconSize);
    PushButton_Style_Set(ui->pb_boost,STYLE_DEFAULT);
    ui->pb_plus->setIcon(QIcon(":/image/plus_.png"));
    ui->pb_plus->setIconSize(buttonIconSize);
    PushButton_Style_Set(ui->pb_plus,STYLE_DEFAULT);
    ui->pb_set->setIcon(QIcon(":/image/set_.png"));
    ui->pb_set->setIconSize(buttonIconSize);
    PushButton_Style_Set(ui->pb_set,STYLE_DEFAULT);
    ui->pb_minus->setIcon(QIcon(":/image/minus_.png"));
    ui->pb_minus->setIconSize(buttonIconSize);
    PushButton_Style_Set(ui->pb_minus,STYLE_DEFAULT);
    ui->pb_power->setIcon(QIcon(":/image/power_.png"));
    ui->pb_power->setIconSize(buttonIconSize);
    PushButton_Style_Set(ui->pb_power,STYLE_DEFAULT);

    ui->cb_orpExist->setCheckState(Qt::Checked);
    ui->cb_pHExist->setCheckState(Qt::Checked);
    // 数据记录文件
    Test_Log_Init();

    Test_Reset();
}

MainWindow::~MainWindow()
{
    delete ui;
    if(m_logFile->isOpen())
    {
        m_logFile->close();
    }
}

void MainWindow::Fill_SerialPort(void)
{
    static QStringList lastPortInfo;
    QStringList portInfo;
    if(modbusDevice->state() != QModbusDevice::ConnectedState)
    {

        for(auto const &info : QSerialPortInfo::availablePorts())
        {
            portInfo.append(info.portName());
        }
        if(lastPortInfo != portInfo)
        {
            lastPortInfo = portInfo;
            ui->cb_serialPort->clear();
            ui->cb_serialPort->addItems(portInfo);
        }
    }
}



void MainWindow::on_pb_openPort_clicked()
{
    if(ui->pb_openPort->text() == "打开")
    {
        modbusDevice->setConnectionParameter(QModbusDevice::SerialPortNameParameter,
                                             ui->cb_serialPort->currentText());
        modbusDevice->setConnectionParameter(QModbusDevice::SerialParityParameter,
                                             QSerialPort::NoParity);
        modbusDevice->setConnectionParameter(QModbusDevice::SerialBaudRateParameter,
                                             QSerialPort::Baud9600);
        modbusDevice->setConnectionParameter(QModbusDevice::SerialDataBitsParameter,
                                             QSerialPort::Data8);
        modbusDevice->setTimeout(100);
        modbusDevice->setNumberOfRetries(0);
        if (modbusDevice->connectDevice())
        {
            Read_Settings(ui->cb_testType->currentIndex());
            ui->pb_openPort->setText("关闭");
            m_serialPortTimer->stop();
            m_testTimer->start(TEST_TIMER_INTERVAL);
            ui->cb_serialPort->setEnabled(false);
            ui->cb_deviceCfg->setEnabled(false);
            ui->cb_electrolytic->setEnabled(false);
            ui->cb_testType->setEnabled(false);
            ui->cb_writeCfg->setEnabled(false);
            ui->cb_pHExist->setEnabled(false);
            ui->cb_orpExist->setEnabled(false);
            ui->dsp_waterTempStd->setEnabled(false);
            ui->dsp_devTempStd->setEnabled(false);
        }
        else
        {
            QString err = "打开失败:";
            err.append('\n');
            err.append(modbusDevice->errorString());
            QMessageBox::critical(this,"错误",err);
        }
    }
    else
    {
        ui->cb_serialPort->setEnabled(true);
        ui->cb_deviceCfg->setEnabled(true);
        ui->cb_electrolytic->setEnabled(true);
        ui->cb_testType->setEnabled(true);
        ui->cb_writeCfg->setEnabled(true);
        ui->cb_pHExist->setEnabled(true);
        ui->cb_orpExist->setEnabled(true);
        ui->dsp_waterTempStd->setEnabled(true);
        ui->dsp_devTempStd->setEnabled(true);
        modbusDevice->disconnectDevice();
        ui->pb_openPort->setText("打开");
        m_serialPortTimer->start(1000);
        m_testTimer->stop();
        Test_Reset();
    }
}

bool MainWindow::Read_Settings(int type)
{
    QFileInfo iniInfo(INISET_FILE);
    if(iniInfo.exists())
    {
        QSettings iniSet(INISET_FILE,QSettings::IniFormat);
        if(type == TEST_PCBA)
        {
            iniSet.beginGroup("PCBA");
            m_valueRange.pH.std = iniSet.value("pH/std").toUInt();
            m_valueRange.pH.range = iniSet.value("pH/range").toUInt();
            m_valueRange.orp.std = iniSet.value("orp/std").toUInt();
            m_valueRange.orp.range = iniSet.value("orp/range").toUInt();
            m_valueRange.waterTemp.std = iniSet.value("waterTemp/std").toUInt();
            m_valueRange.waterTemp.range = iniSet.value("waterTemp/range").toUInt();
            m_valueRange.devTemp.std = iniSet.value("devTemp/std").toUInt();
            m_valueRange.devTemp.range = iniSet.value("devTemp/range").toUInt();
            m_valueRange.sj.std = iniSet.value("sj/std").toUInt();
            m_valueRange.sj.range = iniSet.value("sj/range").toUInt();
            m_valueRange.u.std = iniSet.value("u/std").toUInt();
            m_valueRange.u.range = iniSet.value("u/range").toUInt();
            m_valueRange.i.std = iniSet.value("i/std").toUInt();
            m_valueRange.i.range = iniSet.value("i/range").toUInt();
            m_valueRange.gas.std = iniSet.value("gas/std").toUInt();
            m_valueRange.gas.range = iniSet.value("gas/range").toUInt();
            iniSet.endGroup();
        }
        else
        {
            iniSet.beginGroup("MACHINE");
            m_valueRange.pH.std = iniSet.value("pH/std").toUInt();
            m_valueRange.pH.range = iniSet.value("pH/range").toUInt();
            m_valueRange.orp.std = iniSet.value("orp/std").toUInt();
            m_valueRange.orp.range = iniSet.value("orp/range").toUInt();
            m_valueRange.waterTemp.std = iniSet.value("waterTemp/std").toUInt();
            m_valueRange.waterTemp.range = iniSet.value("waterTemp/range").toUInt();
            m_valueRange.devTemp.std = iniSet.value("devTemp/std").toUInt();
            m_valueRange.devTemp.range = iniSet.value("devTemp/range").toUInt();
            m_valueRange.sj.std = iniSet.value("sj/std").toUInt();
            m_valueRange.sj.range = iniSet.value("sj/range").toUInt();
            m_valueRange.u.std = iniSet.value("u/std").toUInt();
            m_valueRange.u.range = iniSet.value("u/range").toUInt();
            m_valueRange.i.std = iniSet.value("i/std").toUInt();
            m_valueRange.i.range = iniSet.value("i/range").toUInt();
            m_valueRange.gas.std = iniSet.value("gas/std").toUInt();
            m_valueRange.gas.range = iniSet.value("gas/range").toUInt();
            iniSet.endGroup();
        }
        ui->dsp_waterTempStd->setValue(m_valueRange.waterTemp.std/10);
        ui->dsp_devTempStd->setValue(m_valueRange.devTemp.std/10);
        Updata_Settings_Display();
        return true;

    }
    else
    {
        QSettings iniSet(INISET_FILE,QSettings::IniFormat);
        iniSet.beginGroup("PCBA");
        iniSet.setValue("pH/std",540);
        iniSet.setValue("pH/range",100);
        iniSet.setValue("orp/std",392);
        iniSet.setValue("orp/range",60);
        iniSet.setValue("waterTemp/std",250);
        iniSet.setValue("waterTemp/range",30);
        iniSet.setValue("devTemp/std",250);
        iniSet.setValue("devTemp/range",30);
        iniSet.setValue("sj/std",840);
        iniSet.setValue("sj/range",50);
        iniSet.setValue("u/std",3150);
        iniSet.setValue("u/range",50);
        iniSet.setValue("i/std",840);
        iniSet.setValue("i/range",50);
        iniSet.setValue("gas/std",225);
        iniSet.setValue("gas/range",50);
        iniSet.endGroup();

        iniSet.beginGroup("MACHINE");
        iniSet.setValue("pH/std",480);
        iniSet.setValue("pH/range",100);
        iniSet.setValue("orp/std",659);
        iniSet.setValue("orp/range",60);
        iniSet.setValue("waterTemp/std",300);
        iniSet.setValue("waterTemp/range",20);
        iniSet.setValue("devTemp/std",250);
        iniSet.setValue("devTemp/range",30);
        iniSet.setValue("sj/std",840);
        iniSet.setValue("sj/range",50);
        iniSet.setValue("u/std",470);
        iniSet.setValue("u/range",50);
        iniSet.setValue("i/std",840);
        iniSet.setValue("i/range",50);
        iniSet.setValue("gas/std",289);
        iniSet.setValue("gas/range",30);
        iniSet.endGroup();
        return false;
    }
}

void MainWindow::Updata_Settings_Display(void)
{
    ui->lb_ph->setText(QString("pH[%1±%2]").
                       arg(m_valueRange.pH.std/100.0).
                       arg(m_valueRange.pH.range/100.0));

    ui->lb_orp->setText(QString("orp[%1±%2]").
                       arg(m_valueRange.orp.std).
                       arg(m_valueRange.orp.range));
    ui->lb_waterTemp->setText(QString("水温[%1±%2]").
                        arg(m_valueRange.waterTemp.std/10.0).
                        arg(m_valueRange.waterTemp.range/10.0));
    ui->lb_deviceTemp->setText(QString("机箱温度[%1±%2]").
                              arg(m_valueRange.devTemp.std/10.0).
                              arg(m_valueRange.devTemp.range/10.0));
    ui->lb_SJ->setText(QString("SJ[%1±%2]").
                               arg(m_valueRange.sj.std/1000.0).
                               arg(m_valueRange.sj.range/1000.0));
    ui->lb_U->setText(QString("U[%1±%2]").
                       arg(m_valueRange.u.std/100.0).
                       arg(m_valueRange.u.range/100.0));
    ui->lb_I->setText(QString("I[%1±%2]").
                      arg(m_valueRange.i.std/100.0).
                      arg(m_valueRange.i.range/100.0));
    ui->lb_gasSwitch->setText(QString("空气开关[%1±%2]").
                      arg(m_valueRange.gas.std).
                      arg(m_valueRange.gas.range));
}

void MainWindow::Test_Reset(void)
{
    ui->lb_tips->clear();
    ui->lb_error->clear();
    ui->lb_deviceICID->clear();
    ui->lb_deviceType->clear();
    ui->lb_softWare->clear();
    ui->lb_deviceCfg->clear();
    ui->lb_deviceElectrolytic->clear();
    PushButton_Style_Set(ui->pb_power,STYLE_DEFAULT);
    PushButton_Style_Set(ui->pb_minus,STYLE_DEFAULT);
    PushButton_Style_Set(ui->pb_set,STYLE_DEFAULT);
    PushButton_Style_Set(ui->pb_plus,STYLE_DEFAULT);
    PushButton_Style_Set(ui->pb_boost,STYLE_DEFAULT);

    ui->dsp_ph->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->dsp_ph);
    ui->sp_orp->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->sp_orp);
    ui->dsp_waterTemp->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->dsp_waterTemp);
    ui->dsp_deviceTemp->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->dsp_deviceTemp);
    ui->dsp_SJ->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->dsp_SJ);
    ui->dsp_U->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->dsp_U);
    ui->dsp_I->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->dsp_I);
    ui->sp_gasSwitch->setValue(0);
    StyleSheet_Set(STYLE_DEFAULT,ui->sp_gasSwitch);
    ui->le_flow->clear();
    StyleSheet_Set(STYLE_DEFAULT,ui->le_flow);
    ui->le_rtc->clear();
    StyleSheet_Set(STYLE_DEFAULT,ui->le_rtc);
    ui->le_wifi->clear();
    StyleSheet_Set(STYLE_DEFAULT,ui->le_wifi);
    ui->le_dryPoint->clear();
    StyleSheet_Set(STYLE_DEFAULT,ui->le_dryPoint);

    StyleSheet_Set(STYLE_DEFAULT,ui->pb_beep);
    StyleSheet_Set(STYLE_DEFAULT,ui->pb_acidMotor);

    StyleSheet_Set(STYLE_DEFAULT,ui->lb_tips);

    memset(&m_test,0,sizeof(m_test));
    m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
}

void MainWindow::Read_UID()
{
    if (!modbusDevice)
        return;
    if (auto *reply = modbusDevice->sendReadRequest(
        QModbusDataUnit(QModbusDataUnit::InputRegisters,FACTORY_START_ADDR,ICID_LEN),
                                                    FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished())
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_UID_Ready);
        else
            delete reply; // broadcast replies return immediately
    }
}
void MainWindow::On_UID_Ready(void)
{
    uint16_t value;
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        for (qsizetype i = 0, total = unit.valueCount(); i < total; ++i) {
            m_test.uid[i] = unit.value(i);
            qDebug()<<QString("UID%1:").arg(i)<<QString::number(m_test.uid[i],16);
        }
        m_test.uidReadResult = true;
    }
    else
    {
        m_test.uidReadResult = false;
    }

    reply->deleteLater();
}

void MainWindow::Read_IR()
{
    if (!modbusDevice)
        return;
    if (auto *reply = modbusDevice->sendReadRequest(
            QModbusDataUnit(QModbusDataUnit::InputRegisters,CONSUMER_START_ADDR,IR_LEN),
            FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished())
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_IR_Ready);
        else
            delete reply; // broadcast replies return immediately
    }
}

void MainWindow::On_IR_Ready()
{
    uint16_t value;
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        for (qsizetype i = 0, total = unit.valueCount(); i < total; ++i) {
            m_test.ir.ar[i] = unit.value(i);
        }
        if(m_test.testSM == READ_INFO)
        {
            m_test.isInfoRead = true;
        }
        m_test.heartBeatDisconnectCount = 0;
    }
    else
    {
        m_test.heartBeatDisconnectCount++;
        if(m_test.heartBeatDisconnectCount >= HEARTBEAT_TIMEOUT)
        {
            m_test.testSM = TEST_COM_TIMEOUT;       // 结束测试
            m_test.testCountDownTick = 0;
        }
    }
    reply->deleteLater();
}

void MainWindow::Read_GasSw()
{
    if (!modbusDevice)
        return;
    if (auto *reply = modbusDevice->sendReadRequest(
            QModbusDataUnit(QModbusDataUnit::InputRegisters,GAS_SW_ADDR,1),
            FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished())
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_GasSw_Ready);
        else
            delete reply; // broadcast replies return immediately
    }
}
void MainWindow::On_GasSw_Ready()
{
    uint16_t value;
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        m_test.ir.ir.gasSw = unit.value(0);
    }
    reply->deleteLater();
}

void MainWindow::Read_Factory_DI()
{
    if (!modbusDevice)
        return;
    if (auto *reply = modbusDevice->sendReadRequest(
            QModbusDataUnit(QModbusDataUnit::DiscreteInputs,FACTORY_START_ADDR,FACTORY_DI_LEN),
            FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished())
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_Factory_DI_Ready);
        else
            delete reply; // broadcast replies return immediately
    }
}
void MainWindow::On_Factory_DI_Ready()
{
    uint16_t value;
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    if (reply->error() == QModbusDevice::NoError) {
        const QModbusDataUnit unit = reply->result();
        for (qsizetype i = 0, total = FACTORY_DI_LEN; i < total; ++i) {
            m_test.fd.ar[i] = unit.value(i);
        }
    }
    reply->deleteLater();
}

void MainWindow::Write_PassWord()
{
    if (!modbusDevice)
        return;
    QList<uint16_t> writeData;
    writeData.append(m_test.password);

    if (auto *reply = modbusDevice->sendWriteRequest(
            QModbusDataUnit(QModbusDataUnit::HoldingRegisters,FACTORY_START_ADDR,writeData),
                                                     FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished()) {
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_Write_Reply);
        } else {
            reply->deleteLater();
        }
    }
}

void MainWindow::Write_FactoryMode()
{
    if (!modbusDevice)
        return;
    QList<uint16_t> writeData;
    writeData.append(0x01);

    if (auto *reply = modbusDevice->sendWriteRequest(
            QModbusDataUnit(QModbusDataUnit::Coils,FACTORY_START_ADDR,writeData),
            FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished()) {
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_Write_Reply);
        } else {
            reply->deleteLater();
        }
    }
}

void MainWindow::Write_FactoryTestStart(void)
{
    if (!modbusDevice)
        return;
    QList<uint16_t> writeData;
    writeData.append(0x01);

    modbusDevice->sendWriteRequest(
            QModbusDataUnit(QModbusDataUnit::Coils,FACTORY_BEEP_START,writeData),
            FACTORY_MODBUS_ADDR);
}

void MainWindow::Write_FactoryTestStop(void)
{
    if (!modbusDevice)
        return;
    QList<uint16_t> writeData;
    writeData.append(0x01);

    modbusDevice->sendWriteRequest(
        QModbusDataUnit(QModbusDataUnit::Coils,FACTORY_BEEP_END,writeData),
        FACTORY_MODBUS_ADDR);
}

void MainWindow::Write_Control_Signal(void)
{
    uint16_t value = 0;
    if (!modbusDevice)
        return;
    QList<uint16_t> writeData;
    value = m_test.fc.dryPoint;
    writeData.append(value);
    value = m_test.fc.RC;
    writeData.append(value);
    value = m_test.fc.SR;
    writeData.append(value);

    if (auto *reply = modbusDevice->sendWriteRequest(
            QModbusDataUnit(QModbusDataUnit::Coils,CONTROL_SIGNAL_ADDR,writeData),
            FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished()) {
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_Write_Reply);
        } else {
            reply->deleteLater();
        }
    }
}

void MainWindow::Write_Cfg()
{
    if (!modbusDevice)
        return;
    QList<uint16_t> writeData;
    writeData.append(m_deviceCfg);
    writeData.append(m_electrolytic);

    if (auto *reply = modbusDevice->sendWriteRequest(
            QModbusDataUnit(QModbusDataUnit::HoldingRegisters,CFG_START_ADDR,writeData),
            FACTORY_MODBUS_ADDR)) {
        if (!reply->isFinished()) {
            connect(reply, &QModbusReply::finished, this, &MainWindow::On_Write_Reply);
        } else {
            reply->deleteLater();
        }
    }
}

void MainWindow::On_Write_Reply()
{
    auto reply = qobject_cast<QModbusReply *>(sender());
    if (!reply)
        return;

    const auto error = reply->error();
    if (error == QModbusDevice::ProtocolError) {
        ui->lb_error->setText(QString("Write response error: %1 (Modbus exception: 0x%2)")
                                 .arg(reply->errorString()).arg(reply->rawResult().exceptionCode()));
    } else if (error != QModbusDevice::NoError) {
        ui->lb_error->setText(QString("Write response error: %1 (code: 0x%2)")
                                 .arg(reply->errorString()).arg(error, -1, 16));

    }
    else
    {
        m_test.writeResult = true;
    }
    reply->deleteLater();
}

void MainWindow::Calc_PassWord(void)
{
    uint8_t crcBuf[8];
    m_test.crc32Icid = crc32((uint8_t *)m_test.uid, 12);
    qDebug()<<QString::number(m_test.crc32Icid,16);
    m_devId = QString("%1").arg(m_test.crc32Icid,8,16,QLatin1Char('0')).toUpper();
    memcpy(crcBuf,(uint8_t*)&m_test.crc32Icid,4);
    memset(&crcBuf[4],0xFA,4);
    m_test.password = crc16(crcBuf,8);
    qDebug()<<QString::number(m_test.password,16);
    m_uid.clear();
    QString temp;
    temp = QString("%1").arg(m_test.uid[5],4,16,QLatin1Char('0'));
    m_uid.append(temp.toUpper());
    temp = QString("%1").arg(m_test.uid[4],4,16,QLatin1Char('0'));
    m_uid.append(temp.toUpper());
    temp = QString("%1").arg(m_test.uid[3],4,16,QLatin1Char('0'));
    m_uid.append(temp.toUpper());
    temp = QString("%1").arg(m_test.uid[2],4,16,QLatin1Char('0'));
    m_uid.append(temp.toUpper());
    temp = QString("%1").arg(m_test.uid[1],4,16,QLatin1Char('0'));
    m_uid.append(temp.toUpper());
    temp = QString("%1").arg(m_test.uid[0],4,16,QLatin1Char('0'));
    m_uid.append(temp.toUpper());
    // ui->lb_deviceICID->setText(QString("ICID:%1").arg(icid));
}

void MainWindow::Display_Info(void)
{
    QStringList devCfg;
    devCfg<<("F1(INVERTER+MANUAL)")<<("F2(AUTOPH+MANUAL)")<<("F3(SMART+MANUAL)")<<("F4(MANUAL)");
    uint16_t m_electrolyticSpec[4] = {10,16,22,28};
    if(m_test.ir.ir.productType == 2)
    {
        ui->lb_deviceType->setText(QString("设备类型:盐氯机M款"));
    }
    else
    {
        ui->lb_deviceType->setText(QString("设备类型:盐氯机"));
    }

    ui->lb_softWare->setText(QString("软件版本:%1.%2.%3").
                             arg(m_test.ir.ir.softMain).
                             arg((m_test.ir.ir.softSub>>8)&0xFF).
                             arg((m_test.ir.ir.softSub>>0)&0xFF));
    ui->lb_deviceCfg->setText(QString("设备配置:%1").arg(devCfg.at(m_test.ir.ir.productCfg)));
    ui->lb_deviceElectrolytic->setText(QString("电解片规格:%1g").
        arg(m_electrolyticSpec[m_test.ir.ir.electrolyticSpec/10-1]));
}

void MainWindow::Test_Control_Signal_PCBA(void)
{
    if(m_test.controlSignalWriteTick < CONTROL_SIGNAL_WRITE_INTERVAL)
    {
        m_test.controlSignalWriteTick++;
        m_test.testSM = READ_FACTORY_DI;
        // 判断
        switch(m_test.controlStep)
        {
        case 0:
            if(m_test.fd.fd.flowSwitch == 1 &&
                m_test.ir.ir.u >= m_valueRange.u.std - m_valueRange.u.range &&
                m_test.ir.ir.u <= m_valueRange.u.std + m_valueRange.u.range )
            {
                m_test.controlStep++;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        case 1:
            if(m_test.fd.fd.flowSwitch == 0 &&
                m_test.ir.ir.u <= m_valueRange.u.std - m_valueRange.u.range
                 )
            {
                m_test.controlStep++;
                m_test.itemResult.bit.flow = 1;
                m_test.itemResult.bit.dryPoint = 1;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        case 2:
            if(m_test.ir.ir.u >= m_valueRange.u.std - m_valueRange.u.range &&
                m_test.ir.ir.u <= m_valueRange.u.std + m_valueRange.u.range)
            {
                m_test.controlStep++;
                m_test.itemResult.bit.u = 1;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        case 4:

            break;
        }
    }
    else
    {
        m_test.controlSignalWriteTick = 0;
        // RC&SR-->SV   dryPoint --> flow
        switch(m_test.controlStep)
        {
        case 0:
            m_test.fc.dryPoint = 1;
            m_test.fc.RC = 1;
            m_test.fc.SR = 1;
            break;

        case 1:
            m_test.fc.dryPoint = 0;
            m_test.fc.RC = 0;
            m_test.fc.SR = 0;
            break;

        case 2:
            m_test.fc.dryPoint = 1;
            m_test.fc.RC = 1;
            m_test.fc.SR = 1;
            break;

        }
        Write_Control_Signal();
    }
}
void MainWindow::Test_Control_Signal_Machine(void)
{
    if(m_test.controlSignalWriteTick < CONTROL_SIGNAL_WRITE_INTERVAL)
    {
        m_test.controlSignalWriteTick++;
        m_test.testSM = READ_FACTORY_DI;
        // 判断
        switch(m_test.controlStep)
        {
        case 0:
            if(m_test.fd.fd.flowSwitch == 1 &&
                m_test.ir.ir.u >= m_valueRange.u.std - m_valueRange.u.range &&
                m_test.ir.ir.u <= m_valueRange.u.std + m_valueRange.u.range )
            {
                m_test.controlStep++;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"machine step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        case 1:
            if(m_test.fd.fd.flowSwitch == 0 &&
                m_test.ir.ir.u <= m_valueRange.u.std - m_valueRange.u.range
                )
            {
                m_test.controlStep++;
                m_test.itemResult.bit.flow = 1;
                m_test.itemResult.bit.dryPoint = 1;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"machine step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        case 2:
            if(m_test.ir.ir.u >= m_valueRange.u.std - m_valueRange.u.range &&
                m_test.ir.ir.u <= m_valueRange.u.std + m_valueRange.u.range)
            {
                m_test.controlStep++;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"machine step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        case 3:
            if(m_test.ir.ir.u <= m_valueRange.u.std - m_valueRange.u.range)
            {
                m_test.controlStep++;
                m_test.itemResult.bit.u = 1;
                m_test.controlSignalWriteTick = CONTROL_SIGNAL_WRITE_INTERVAL;
            }
            qDebug()<<"machine step"<<m_test.controlStep<<"flow:"<<m_test.fd.fd.flowSwitch<<"U:"<<m_test.ir.ir.u;
            break;

        }
    }
    else
    {
        m_test.controlSignalWriteTick = 0;
        switch(m_test.controlStep)
        {
        case 0:
            m_test.fc.dryPoint = 1;
            m_test.fc.RC = 1;
            m_test.fc.SR = 1;
            break;

        case 1:
            m_test.fc.dryPoint = 0;
            m_test.fc.RC = 0;
            m_test.fc.SR = 1;
            break;

        case 2:
            m_test.fc.dryPoint = 1;
            m_test.fc.RC = 1;
            m_test.fc.SR = 0;
            break;

        case 3:
            m_test.fc.dryPoint = 1;
            m_test.fc.RC = 0;
            m_test.fc.SR = 0;
            break;

        case 4:
            m_test.fc.dryPoint = 1;
            m_test.fc.RC = 1;
            m_test.fc.SR = 0;
            break;

        }
        Write_Control_Signal();
    }
}

bool MainWindow::Test_Control_Signal(void)
{
    if(m_testType == TEST_PCBA)
    {
        Test_Control_Signal_PCBA();
    }
    else if(m_testType == TEST_MACHINE)
    {
        Test_Control_Signal_Machine();
    }
    return true;
}


void MainWindow::Control_Dev_Enter_FactoryMode(void)
{
    switch (m_test.connectSM)
    {
    case CONNECT_START:
        ui->lb_tips->setText("开始连接设备......");
        m_test.connectSM = READ_UID;
        break;

    case READ_UID:
        if(m_test.uidReadResult)
        {
            m_test.connectSM = CALC_PASSWORD;
        }
        else
        {
            ui->lb_tips->setText("读取UID");
            Read_UID();
            break;
        }

    case CALC_PASSWORD:
        Calc_PassWord();
        m_test.writeResult = false;
        m_test.connectSM = WRITE_PASSWORD;
        // break;

    case WRITE_PASSWORD:
        if(m_test.writeResult)
        {
            m_test.connectSM = ENTER_FACTORY;
            m_test.writeResult = false;
        }
        else
        {
            Write_PassWord();
        }
        break;

    case ENTER_FACTORY:
        if(m_test.writeResult)
        {
            Write_FactoryTestStart();
            m_test.connectSM = CONNECT_START;
            m_test.isInFactoryMode = true;  
            qDebug()<<"enter factor mode";
            ui->lb_tips->setText("进入测试模式");
        }
        else
        {
            ui->lb_tips->setText("进入测试模式......");
            Write_FactoryMode();
        }
        break;

    default:
        break;
    }
}

void MainWindow::Dev_Test_Process(void)
{
    switch(m_test.testSM)
    {
    case TEST_START:
        ui->lb_tips->setText("开始测试！");
        m_test.testCountDownTick = TEST_COUNT_DOWN_START;
        m_test.isInfoRead = false;
        if(m_writeCfg)
        {
            m_test.testSM = WRITE_CFG;
            m_test.writeResult = false;
        }
        else
        {
            m_test.testSM = READ_INFO;
        }
        break;

    case WRITE_CFG:
        if(m_test.writeResult)
        {
            m_test.testSM = READ_INFO;
            qDebug()<<"write cfg success";
        }
        else
        {
            Write_Cfg();
        }
        break;

    case READ_INFO:
        if(m_test.isInfoRead)
        {
            Display_Info();
            m_test.testSM = READ_IR;
        }
        else
        {
            Read_IR();
        }
        break;

    case READ_IR:
        Read_IR();
        m_test.testSM = READ_GAS_SW_IR;
        break;

    case READ_GAS_SW_IR:
        Read_GasSw();
        m_test.testSM = WRITE_CONTROL_SIGNAL;
        m_test.writeResult = false;
        break;

    case WRITE_CONTROL_SIGNAL:
        Test_Control_Signal();
        m_test.testSM = READ_FACTORY_DI;
        break;

    case READ_FACTORY_DI:
        Read_Factory_DI();
        m_test.testSM = READ_IR;
        break;

    case TEST_PASS:
        ui->lb_tips->setText("测试通过");
        Write_FactoryTestStop();
        Test_Result_Display();
        m_test.uidReadResult = true;
        Test_Log_Write();
        m_test.testSM = TEST_WAIT_DEV_DISCONNECT;
        return;

    case TEST_TIMEOUT:
        ui->lb_tips->setText(QString("测试失败,请重试!"));
        StyleSheet_Set(STYLE_FAIL,ui->lb_tips);
        m_test.uidReadResult = true;
        Test_Log_Write();
        m_test.testSM = TEST_WAIT_DEV_DISCONNECT;
        return;

    case TEST_COM_TIMEOUT:
        ui->lb_tips->setText(QString("通讯超时,请检查485连接!"));
        StyleSheet_Set(STYLE_FAIL,ui->lb_tips);
        m_test.uidReadResult = false;
        Test_Log_Write();
        m_test.testSM = TEST_WAIT_DEV_CONNECT;
        return;

    case TEST_WAIT_DEV_DISCONNECT:
        Read_UID();
        if(m_test.uidReadResult)
        {
        }
        else
        {
            Test_Reset();
        }
        return;

    case TEST_WAIT_DEV_CONNECT:
        if(m_test.uidReadResult)
        {
            Test_Reset();
        }
        else
        {
            Read_UID();
        }
        return;

    }

    // 测试超时
    if(m_test.testCountDownTick)
    {
        m_test.testCountDownTick--;
        ui->lb_tips->setText(QString("测试倒计时:%1s").
                             arg(m_test.testCountDownTick/(1000/TEST_TIMER_INTERVAL)));
    }
    else
    {
        m_test.testSM = TEST_TIMEOUT;
        return;
    }

    Test_Result_Check();
    Test_Result_Display();
}

void MainWindow::Test_Main(void)
{
    if(m_test.isInFactoryMode)
    {
        Dev_Test_Process();
    }
    else
    {
        Control_Dev_Enter_FactoryMode();
    }
}

void MainWindow::on_cb_deviceCfg_currentIndexChanged(int index)
{
    m_deviceCfg = index;
    qDebug()<<"dev configure:"<<QString::number(index);
}


void MainWindow::on_cb_electrolytic_currentIndexChanged(int index)
{
    m_electrolytic = (index+1)*10;
    qDebug()<<"Electorlysis Spec:"<<QString::number(index);
}


void MainWindow::on_cb_testType_currentIndexChanged(int index)
{
    m_testType = index;
    Read_Settings(index);
    qDebug()<<"Test Configure:"<<QString::number(index);
}

void MainWindow::StyleSheet_Set(test_style style,QWidget* w)
{
    switch(style)
    {
    case STYLE_DEFAULT:
        w->setStyleSheet(defaultStyle);
        break;

    case STYLE_FAIL:
        w->setStyleSheet(failStyle);
        break;

    case STYLE_PASS:
        w->setStyleSheet(passStyle);
        break;
    }
}


void MainWindow::PushButton_Style_Set(QPushButton* b,enum test_style style)
{
    QString defaultStyle = "QPushButton{border:2px groove white;border-radius: 25px;color: black;background-color: white;}";
    QString passStyle = "QPushButton{border:2px groove white;border-radius: 25px;color: black;background-color: springgreen;}";
    QString failStyle = "QPushButton{border:2px groove white;border-radius: 25px;color: black;background-color: red;}";
    switch(style)
    {
    case STYLE_DEFAULT:
        b->setStyleSheet(defaultStyle);
        break;
    case STYLE_PASS:
        b->setStyleSheet(passStyle);
        break;
    case STYLE_FAIL:
        b->setStyleSheet(failStyle);
        break;
    }
}

void MainWindow::Test_Result_Check(void)
{

    if(m_test.fd.fd.keyPower)
    {
        m_test.itemResult.bit.keyPower = true;
    }
    if(m_test.fd.fd.keyMinus)
    {
        m_test.itemResult.bit.keyMinus = true;
    }
    if(m_test.fd.fd.keySet)
    {
        m_test.itemResult.bit.keySet = true;
    }
    if(m_test.fd.fd.keyPlus)
    {
        m_test.itemResult.bit.keyPlus = true;
    }
    if(m_test.fd.fd.keyBoost)
    {
        m_test.itemResult.bit.keyBoost = true;
    }

    if(m_test.fd.fd.beepTest)
    {
        m_test.itemResult.bit.beep = true;
    }

    if(m_test.fd.fd.motorTest)
    {
        m_test.itemResult.bit.acidMotor = true;
    }
    // 水流开关不在这里判断

    if(m_test.fd.fd.rtcTest)
    {
        m_test.itemResult.bit.RTC = true;
    }
    else
    {
        m_test.itemResult.bit.RTC = false;
    }

    if(m_test.fd.fd.wifiTest)
    {
        m_test.itemResult.bit.WIFI = true;
    }
    else
    {
        m_test.itemResult.bit.WIFI = false;
    }

    // 干接点不在这里判断

    if(m_test.ir.ir.ph >= m_valueRange.pH.std - m_valueRange.pH.range &&
        m_test.ir.ir.ph <= m_valueRange.pH.std + m_valueRange.pH.range )
    {
        m_test.itemResult.bit.pH = true;
    }
    else
    {
        m_test.itemResult.bit.pH = false;
    }

    if(m_test.ir.ir.orp >= m_valueRange.orp.std - m_valueRange.orp.range &&
        m_test.ir.ir.orp <= m_valueRange.orp.std + m_valueRange.orp.range )
    {
        m_test.itemResult.bit.orp = true;
    }
    else
    {
        m_test.itemResult.bit.orp = false;
    }

    if(m_test.ir.ir.waterTemp >= m_valueRange.waterTemp.std - m_valueRange.waterTemp.range &&
        m_test.ir.ir.waterTemp <= m_valueRange.waterTemp.std + m_valueRange.waterTemp.range )
    {
        m_test.itemResult.bit.waterTemp = true;
    }
    else
    {
        m_test.itemResult.bit.waterTemp = false;
    }

    if(m_test.ir.ir.devTemp >= m_valueRange.devTemp.std - m_valueRange.devTemp.range &&
        m_test.ir.ir.devTemp <= m_valueRange.devTemp.std + m_valueRange.devTemp.range )
    {
        m_test.itemResult.bit.devTemp = true;
    }
    else
    {
        m_test.itemResult.bit.devTemp = false;
    }

    if(m_test.ir.ir.gasSw >= m_valueRange.gas.std - m_valueRange.gas.range &&
        m_test.ir.ir.gasSw <= m_valueRange.gas.std + m_valueRange.gas.range )
    {
        m_test.itemResult.bit.gas = true;
    }
    else
    {
        m_test.itemResult.bit.gas = false;
    }

    if(m_test.ir.ir.i >= m_valueRange.i.std - m_valueRange.i.range &&
        m_test.ir.ir.i <= m_valueRange.i.std + m_valueRange.i.range )
    {
        m_test.itemResult.bit.i = true;
        m_test.itemResult.bit.sj = true;
    }
    else
    {
        m_test.itemResult.bit.i = false;
        m_test.itemResult.bit.sj = false;
    }

    if((m_test.itemResult.word & m_resultMask) == m_resultMask)
    {
        m_test.testResult = true;
        m_test.testSM = TEST_PASS;
    }
    else
    {
        m_test.testResult = false;
    }


}

void MainWindow::Test_Result_Testing_Display(void)
{

    // 5个按键显示
    if(m_test.itemResult.bit.keyPower)
    {
        PushButton_Style_Set(ui->pb_power,STYLE_PASS);
    }
    if(m_test.itemResult.bit.keyMinus)
    {
        PushButton_Style_Set(ui->pb_minus,STYLE_PASS);
    }
    if(m_test.itemResult.bit.keySet)
    {
        PushButton_Style_Set(ui->pb_set,STYLE_PASS);
    }
    if(m_test.itemResult.bit.keyPlus)
    {
        PushButton_Style_Set(ui->pb_plus,STYLE_PASS);
    }
    if(m_test.itemResult.bit.keyBoost)
    {
        PushButton_Style_Set(ui->pb_boost,STYLE_PASS);
    }

    //
    if(m_test.itemResult.bit.pH)
    {
        StyleSheet_Set(STYLE_PASS,ui->dsp_ph);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->dsp_ph);
    }

    if(m_test.itemResult.bit.orp)
    {
        StyleSheet_Set(STYLE_PASS,ui->sp_orp);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->sp_orp);
    }

    if(m_test.itemResult.bit.waterTemp)
    {
        StyleSheet_Set(STYLE_PASS,ui->dsp_waterTemp);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->dsp_waterTemp);
    }

    if(m_test.itemResult.bit.devTemp)
    {
        StyleSheet_Set(STYLE_PASS,ui->dsp_deviceTemp);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->dsp_deviceTemp);
    }

    if(m_test.itemResult.bit.sj)
    {
        StyleSheet_Set(STYLE_PASS,ui->dsp_SJ);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->dsp_SJ);
    }

    if(m_test.itemResult.bit.u)
    {
        StyleSheet_Set(STYLE_PASS,ui->dsp_U);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->dsp_U);
    }

    if(m_test.itemResult.bit.i)
    {
        StyleSheet_Set(STYLE_PASS,ui->dsp_I);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->dsp_I);
    }

    if(m_test.itemResult.bit.gas)
    {
        StyleSheet_Set(STYLE_PASS,ui->sp_gasSwitch);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->sp_gasSwitch);
    }

    if(m_test.itemResult.bit.flow)
    {
        StyleSheet_Set(STYLE_PASS,ui->le_flow);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->le_flow);
    }

    if(m_test.itemResult.bit.WIFI)
    {
        StyleSheet_Set(STYLE_PASS,ui->le_wifi);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->le_wifi);
    }

    if(m_test.itemResult.bit.RTC)
    {
        StyleSheet_Set(STYLE_PASS,ui->le_rtc);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->le_rtc);
    }

    if(m_test.itemResult.bit.dryPoint)
    {
        StyleSheet_Set(STYLE_PASS,ui->le_dryPoint);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->le_dryPoint);
    }

    if(m_test.itemResult.bit.beep)
    {
        StyleSheet_Set(STYLE_PASS,ui->pb_beep);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->pb_beep);
    }
    if(m_test.itemResult.bit.acidMotor)
    {
        StyleSheet_Set(STYLE_PASS,ui->pb_acidMotor);
    }
    else
    {
        StyleSheet_Set(STYLE_FAIL,ui->pb_acidMotor);
    }

    if(m_test.testResult)
    {
        StyleSheet_Set(STYLE_PASS,ui->lb_tips);
    }
}

void MainWindow::Test_Result_Display(void)
{
    bool last,cur;
    // 数值显示
    ui->dsp_ph->setValue(m_test.ir.ir.ph/100.0);
    ui->sp_orp->setValue(m_test.ir.ir.orp);
    ui->dsp_waterTemp->setValue(m_test.ir.ir.waterTemp/10.0);
    ui->dsp_deviceTemp->setValue(m_test.ir.ir.devTemp/10.0);
    ui->dsp_SJ->setValue(m_test.ir.ir.sj/1000.0);
    ui->dsp_U->setValue(m_test.ir.ir.u/100.0);
    ui->dsp_I->setValue(m_test.ir.ir.i/100.0);
    ui->sp_gasSwitch->setValue((m_test.ir.ir.gasSw));
    if(m_test.fd.fd.wifiTest)
    {
        ui->le_wifi->setText("ON");
    }
    else
    {
        ui->le_wifi->setText("OFF");
    }
    if(m_test.fd.fd.rtcTest)
    {
        ui->le_rtc->setText("ON");
    }
    else
    {
        ui->le_rtc->setText("OFF");
    }
    if(m_test.fd.fd.flowSwitch)
    {
        ui->le_flow->setText("ON");
    }
    else
    {
        ui->le_flow->setText("OFF");
    }
    if(m_test.fc.dryPoint == 1)
    {
        ui->le_dryPoint->setText("ON");
    }
    else
    {
        ui->le_dryPoint->setText("OFF");
    }


    Test_Result_Testing_Display();


}

void MainWindow::on_cb_writeCfg_checkStateChanged(const Qt::CheckState &arg1)
{
    if(arg1 == Qt::Unchecked)
    {
        m_writeCfg = false;
    }
    else if(arg1 == Qt::Checked)
    {
        m_writeCfg = true;
    }

}

void MainWindow::Test_Log_Init()
{
    QString dirName = QDir::currentPath()+"/log/";
    QDir dir(dirName);
    QString fileName = QDate::currentDate().toString("yyyy-MM-dd")+".csv";
    fileName.prepend(dirName);
    m_logFile = new QFile(fileName);
    if(!dir.exists())
    {
        dir.mkdir(dirName);
    }
    if(m_logFile->exists())
    {
        if(!m_logFile->open(QIODevice::Append))
        {
            QMessageBox::information(this,"提醒","记录文件打开失败");
        }
    }
    else
    {
        if(!m_logFile->open(QIODevice::Append))
        {
            QMessageBox::information(this,"提醒","记录文件打开失败");
        }
        QTextStream logStream(m_logFile);
        logStream<<"time,result,uid,devid,pH,ORP,waterTemp,devTemp,SJ,U,I,gas,flow,wifi,rtc,drypoint,beep,acidmotor,keypower,keyminus,keyset,keyplus,keyboost"
                  <<"\n";
    }
}
void MainWindow::Test_Log_Write()
{
    QTextStream logStream(m_logFile);
    logStream<<QTime::currentTime().toString("HH:mm:ss")<<","<<m_test.testResult<<","
              <<m_uid<<","<<m_devId<<","<<m_test.ir.ir.ph<<","
              <<m_test.ir.ir.orp<<","<<m_test.ir.ir.waterTemp<<","
              <<m_test.ir.ir.devTemp<<","
              <<m_test.ir.ir.sj<<","<<m_test.ir.ir.u<<","<<m_test.ir.ir.i<<","
              <<m_test.ir.ir.gasSw<<","<<m_test.itemResult.bit.flow<<","
              <<m_test.itemResult.bit.WIFI<<","<<m_test.itemResult.bit.RTC<<","
              <<m_test.itemResult.bit.dryPoint<<","<<m_test.itemResult.bit.beep<<","
              <<m_test.itemResult.bit.acidMotor<<","<<m_test.itemResult.bit.keyPower<<","
              <<m_test.itemResult.bit.keyMinus<<","<<m_test.itemResult.bit.keySet<<","
              <<m_test.itemResult.bit.keyPlus<<","<<m_test.itemResult.bit.keyBoost
              <<"\n";
}

void MainWindow::on_pb_beep_clicked()
{
    m_test.itemResult.bit.beep = true;
}


void MainWindow::on_pb_acidMotor_clicked()
{
    m_test.itemResult.bit.acidMotor = true;
}


void MainWindow::on_cb_orpExist_checkStateChanged(const Qt::CheckState &arg1)
{
    if(arg1 == Qt::Checked)
    {
        m_orpExist = true;
        m_resultMask |= (0x01<<ORP_RESULT_POS);
        qDebug()<<QString::number(m_resultMask,16);
        ui->lb_orp->show();
        ui->sp_orp->show();
    }
    else
    {
        m_orpExist = false;
        m_resultMask &= (~(0x01<<ORP_RESULT_POS));
        qDebug()<<QString::number(m_resultMask,16);
        ui->lb_orp->hide();
        ui->sp_orp->hide();
    }

}


void MainWindow::on_cb_pHExist_checkStateChanged(const Qt::CheckState &arg1)
{
    if(arg1 == Qt::Checked)
    {
        m_pHExist = true;
        m_resultMask |= (0x01<<PH_RESULT_POS);
        m_resultMask |= (0x01<<WATER_TEMP_RESULT_POS);
        qDebug()<<QString::number(m_resultMask,16);
        ui->lb_ph->show();
        ui->dsp_ph->show();
        ui->lb_waterTemp->show();
        ui->dsp_waterTemp->show();
    }
    else
    {
        m_pHExist = false;
        m_resultMask &= (~(0x01<<PH_RESULT_POS));
        m_resultMask &= (~(0x01<<WATER_TEMP_RESULT_POS));
        qDebug()<<QString::number(m_resultMask,16);
        ui->lb_ph->hide();
        ui->dsp_ph->hide();
        ui->lb_waterTemp->hide();
        ui->dsp_waterTemp->hide();
    }
}


void MainWindow::on_dsp_waterTempStd_valueChanged(double arg1)
{
    m_valueRange.waterTemp.std = arg1*10;
    QSettings iniSet(INISET_FILE,QSettings::IniFormat);
    if(ui->cb_testType->currentText() == "PCBA")
    {
        iniSet.beginGroup("PCBA");
        iniSet.setValue("waterTemp/std",m_valueRange.waterTemp.std);
        iniSet.endGroup();
    }
    else if(ui->cb_testType->currentText() == "整机")
    {
        iniSet.beginGroup("MACHINE");
        iniSet.setValue("waterTemp/std",m_valueRange.waterTemp.std);
        iniSet.endGroup();
    }

    Updata_Settings_Display();
}


void MainWindow::on_dsp_devTempStd_valueChanged(double arg1)
{
    m_valueRange.devTemp.std = arg1*10;
    QSettings iniSet(INISET_FILE,QSettings::IniFormat);
    if(ui->cb_testType->currentText() == "PCBA")
    {
        iniSet.beginGroup("PCBA");
        iniSet.setValue("devTemp/std",m_valueRange.devTemp.std);
        iniSet.endGroup();
    }
    else if(ui->cb_testType->currentText() == "整机")
    {
        iniSet.beginGroup("MACHINE");
        iniSet.setValue("devTemp/std",m_valueRange.devTemp.std);
        iniSet.endGroup();
    }
    Updata_Settings_Display();
}


void MainWindow::on_pb_help_clicked()
{
    QString helpFile = "./help/";
    if(ui->cb_testType->currentText() == "PCBA")
    {
        helpFile.append(PCBA_HELP);
    }
    else if(ui->cb_testType->currentText() == "整机")
    {
        helpFile.append(QString(MACHINE_HELP));
    }
    QDesktopServices::openUrl(QUrl::fromLocalFile(helpFile));
}

